package com.base.myproject.client.tools;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.base.myproject.client.busi.BO.BaseObject;
import com.base.myproject.client.busi.BO.BusiObject;
import com.base.myproject.client.busi.business.RatifyInfo;
import com.base.myproject.client.jdbc.StoreInfo;
import com.base.myproject.client.system.Env;
import com.extjs.gxt.ui.client.data.BasePagingLoadResult;
import com.extjs.gxt.ui.client.data.BasePagingLoader;
import com.extjs.gxt.ui.client.data.DataField;
import com.extjs.gxt.ui.client.data.HttpProxy;
import com.extjs.gxt.ui.client.data.ListLoadResult;
import com.extjs.gxt.ui.client.data.ModelData;
import com.extjs.gxt.ui.client.data.ModelType;
import com.extjs.gxt.ui.client.data.PagingLoadConfig;
import com.extjs.gxt.ui.client.data.PagingLoadResult;
import com.extjs.gxt.ui.client.data.XmlReader;
import com.google.gwt.core.client.GWT;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.http.client.Response;
import com.google.gwt.http.client.URL;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.xml.client.Document;
import com.google.gwt.xml.client.Element;
import com.google.gwt.xml.client.Node;
import com.google.gwt.xml.client.NodeList;
import com.google.gwt.xml.client.XMLParser;
/**
 * 向服务器发送请求
 * @author zgw
 *2009-6-21 下午02:46:48
 * javazgw@gmail.com
 */
public class SendServlet {

	public SendServlet()
	{
		
	}
	
	
	/**
	 * 	sendservlet.sendServlet("BaseServlet", "Action=test", new RequestCallback())

	 * @param url
	 * @param form
	 * @param rcb
	 * @return
	 * @throws RequestException
	 */
	public boolean sendServlet(String url,String form,RequestCallback rcb) throws RequestException
	{
		
		return sendServlet(url,form,null,null,rcb);

	}
	/**
	 * 录入用户名和密码的请求
	 * sendservlet.sendServlet("BaseServlet", "Action=test","root","1", new RequestCallback())
	 * @param url
	 * @param form
	 * @param user
	 * @param pass
	 * @param rcb
	 * @return
	 * @throws RequestException
	 */
	@Deprecated
	public boolean sendServlet(String url,String form,String user,String pass,RequestCallback rcb) throws RequestException
	{

	
		String str = "";
		str = GWT.getModuleBaseURL().substring(GWT.getModuleBaseURL().indexOf(GWT.getHostPageBaseURL())+GWT.getHostPageBaseURL().length()-1);
		
		System.out.println("str="+str);
		RequestBuilder builder = new RequestBuilder(RequestBuilder.POST,URL.encode(url));  
		builder.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");  
		
		if(user!=null)
			builder.setUser(user);
		if(pass!=null)
			builder.setPassword(pass);
//		if(Env.getUid()!=null)
//		form+="&system_uuid="+Env.getUid();
		
		form+="&"+Env.getFormParams();
		builder.sendRequest(form,rcb);  
		return true;
	}
	public   String getStringx(String servleturl,String servletdata){

		//解决 http://127.0.0.1:8080/app/manager.html的问题，
		String str = "";
		str = GWT.getModuleBaseURL().substring(GWT.getModuleBaseURL().indexOf(GWT.getHostPageBaseURL())+GWT.getHostPageBaseURL().length()-1);
		servletdata+="&"+Env.getFormParams();
		
		//Window.alert("SendServlet2");
		return getString(servleturl,servletdata);
	}
	/**
	 * 如同com.google.gwt.http.client.XMLHTTPRequest
	 * jquery比较简洁于是用jquery方法，另外一个原因是我在不熟悉gwt的情况下找了同步的ajax
	 * 请求花费了我太多时间至少1.5天
	 * 
	 * 同步的ajax请求
	 *   servleturl: "/gwtbase/BaseServlet", 注意2010-2-1 改，/BaseServlet 前部分程序自己组合
     *   servletdata:"Action=getdatawin",
	 * @param servleturl
	 * @param servletdata
	 * 
	 * @return
	 */
	 @SuppressWarnings("unused")
	private  native String getString(String servleturl,String servletdata) /*-{ 
		
		var str = $wnd.$.ajax({
	      url: servleturl,
	     data: servletdata,
	      type: "POST",
	     async: false,
	      dataType: "xml",
	      success: function(msg){
	         
	      }
	   }
	).responseText;

	return str;
		 }-*/;
	 
	 public  BasePagingLoader< PagingLoadResult<ModelData>> getBaseLoader(final ModelType type,StoreInfo storeinfo ) {
		return  getBaseLoader(type,storeinfo,true);
	 }
	 /**
	  * 分组的Grid所用到的loader
	  * @param type
	  * @param storeinfo
	  * @return
	  */
	 public  BasePagingLoader< PagingLoadResult<ModelData>> getBaseLoader(final ModelType type,StoreInfo storeinfo,boolean needencode) {
			Date date = new Date();
			RequestBuilder builder;
			if(needencode)
			{
			 builder = new RequestBuilder(RequestBuilder.POST,
					URL.encode("gwtbase/BaseServlet?Action=Loaddata"+"&"+storeinfo.getStoreInfoString()));
			}
			else
			{
				 builder = new RequestBuilder(RequestBuilder.POST,
							"gwtbase/BaseServlet?Action=Loaddata"+"&"+storeinfo.getStoreInfoString());
					}
			builder.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");  

			builder.setCallback(new RequestCallback(){

				@Override
				public void onError(Request request, Throwable exception) {
					// TODO Auto-generated method stub
					System.out.println("error.....");
				}

				@Override
				public void onResponseReceived(Request request, Response response) {
					// 
					
				
				}});
			HttpProxy proxy = new HttpProxy(builder);

			// need a loader, proxy, and reader
			XmlReader reader = new XmlReader( type)
			{
				
				protected ListLoadResult newLoadResult(Object loadConfig, List models) { 
						PagingLoadConfig pagingConfig = (PagingLoadConfig) loadConfig; 
						PagingLoadResult <ModelData> result = new BasePagingLoadResult<ModelData>(models, 
						pagingConfig.getOffset(), pagingConfig.getLimit()); 
						 
						return result; 
						} 
				@Override 
				 public ListLoadResult read(Object loadConfig, Object data) {
					    Document doc = XMLParser.parse((String) data);

					    NodeList list = doc.getElementsByTagName(type.getRecordName());
					    ArrayList<ModelData> records = new ArrayList<ModelData>();
					    for (int i = 0; i < list.getLength(); i++) {
					      Node node = list.item(i);
					      Element elem = (Element) node;
					      ModelData model = newModelInstance();
					      for (int j = 0; j < type.getFieldCount(); j++) {
					        DataField field = type.getField(j);
					        String map = field.getMap() != null ? field.getMap() : field.getName();
					        String v = getValue(elem, map);
					        model.set(field.getName(), v);
					      }
					      records.add(model);
					    }

					    int totalCount = records.size();

					    Node root = doc.getElementsByTagName(type.getRoot()).item(0);
					    if (root != null && type.getTotalName() != null) {
					      Node totalNode = root.getAttributes().getNamedItem(type.getTotalName());
					      if (totalNode != null) {
					        String sTot = totalNode.getNodeValue();
					        totalCount = Integer.parseInt(sTot);
					      }
					    }
					    //获得自曾字段的值
					 
			/*		    if (root != null ) {
						      Node totalNode = root.getAttributes().getNamedItem("autoinc");
						      if (totalNode != null) {
						         autoinc = totalNode.getNodeValue();
						         System.out.println("----------z "+autoinc);
						       }
						    }*/
					    ListLoadResult result = newLoadResult(loadConfig, records);
					    if (result instanceof PagingLoadResult) {
					      PagingLoadResult r = (PagingLoadResult) result;
					      r.setTotalLength(totalCount);
					    }
					    return result;
					  }
						
				
			};
	 BasePagingLoader<  PagingLoadResult<ModelData>>  loader = new BasePagingLoader<  PagingLoadResult<ModelData>> (proxy,reader);  

			return loader;
		}
	 
	 /**
	  * 分组显示的loader，采用了BusiObject
	  * @param type
	  * @param storeinfoloader
	  * @return
	  */
	 @SuppressWarnings("unchecked")
		public BasePagingLoader<PagingLoadResult<BusiObject>> getBaseLoaderX(final ModelType type,
				final StoreInfo storeinfoloader) {
			Date date = new Date();
			// System.out.println("客户端发送数据请求=="+date.getTime()/1000+"--"+storeinfo.getStoreInfoString());
//			RequestBuilder builder = new RequestBuilder(RequestBuilder.POST,
//					"BaseServlet?Action=Loaddata" + "&"
//							+ storeinfoloader.getStoreInfoString());
			
			RequestBuilder builder = new RequestBuilder(RequestBuilder.POST,
			"gwtbase/BaseServlet");
			// System.out.println("storeinfo="+URL.encode("BaseServlet?Action=Loaddata"+"&"+storeinfo.getStoreInfoString()));
			// System.out.println("storeinfo="+"BaseServlet?Action=Loaddata"+"&"+storeinfo.getStoreInfoString());
			// System.out.println("ddd"+URL.encode("+"));
			// System.out.println("ddd"+URL.decode(URL.encode("+")));
			builder.setHeader("Content-Type",
					"application/x-www-form-urlencoded;charset=utf-8");

			builder.setCallback(new RequestCallback() {

				@Override
				public void onError(Request request, Throwable exception) {
					// TODO Auto-generated method stub
					System.out.println("error.....");
				}

				@Override
				public void onResponseReceived(Request request, Response response) {
					// 

				}
			});
			HttpProxy proxy = new HttpProxy(builder);

			// need a loader, proxy, and reader
			XmlReader reader = new XmlReader(type) {

				protected ListLoadResult newLoadResult(Object loadConfig,
						List models) {
					PagingLoadConfig pagingConfig = (PagingLoadConfig) loadConfig;
					PagingLoadResult<BusiObject> result = new BasePagingLoadResult<BusiObject>(
							models, pagingConfig.getOffset(), pagingConfig
									.getLimit());

					return result;
				}

				@Override
				public ListLoadResult read(Object loadConfig, Object data) {

					Document doc = XMLParser.parse((String) data);

					NodeList list = doc.getElementsByTagName(type
							.getRecordName());
					ArrayList<ModelData> records = new ArrayList<ModelData>();
					for (int i = 0; i < list.getLength(); i++) {
						Node node = list.item(i);
						Element elem = (Element) node;
						ModelData model = newModelInstance();
						for (int j = 0; j < type.getFieldCount(); j++) {
							DataField field = type.getField(j);
							String map = field.getMap() != null ? field.getMap()
									: field.getName();
							String v = getValue(elem, map);
							/**
							 * 如果是BaseObject类或者其子类，这调用setNotFlag ，避免在初始化的时候也插入了标识
							 */
							if(model instanceof BaseObject)
							{
								((BusiObject)model).setNotFlag(field.getName(), v);
							}
							else
							{
							model.set(field.getName(), v);
							}
						}
						/**
						 * 如果是BusiObject 那么要设置主键的原始值，方便增删改操作
						 */
						if(model instanceof BusiObject)
						{
							
							if (((BusiObject) model).getStoreinfo() == null)

							{
								GWT.log("没有设置主键，不能保存", null);
							} else {
								String[] keyarray = ((BusiObject) model)
										.getStoreinfo().getKeyname();
								if (keyarray != null) {
									for (int k = 0; k < keyarray.length; k++) {
										((BusiObject) model).put(keyarray[k],
												getValue(elem, keyarray[k]));
									}
								}
							}
						}
						records.add(model);
					}

					int totalCount = records.size();

					Node root = doc.getElementsByTagName(type.getRoot()).item(
							0);
					if (root != null && type.getTotalName() != null) {
						Node totalNode = root.getAttributes().getNamedItem(
								type.getTotalName());
						if (totalNode != null) {
							String sTot = totalNode.getNodeValue();
							totalCount = Integer.parseInt(sTot);
						}
					}
					// 获得自曾字段的值

				/*	if (root != null) {
						Node totalNode = root.getAttributes().getNamedItem(
								"autoinc");
						if (totalNode != null) {
							autoinc = totalNode.getNodeValue();
							System.out.println("----------z " + autoinc);
						}
					}*/
					ListLoadResult result = newLoadResult(loadConfig, records);
					if (result instanceof PagingLoadResult) {
						PagingLoadResult r = (PagingLoadResult) result;
						//r.setTotalLength(totalCount);
					//	setTotlerowcount(totalCount + "");
					}
					return result;
				}

				protected ModelData newModelInstance() {
				
						return new BusiObject(storeinfoloader);
				
					
				}
			};

			// BasePagingLoader<PagingLoadResult<ModelData>> loader = new
			// BasePagingLoader<PagingLoadResult<ModelData>>(proxy,reader);

			BasePagingLoader<PagingLoadResult<BusiObject>> loader = new BasePagingLoader<PagingLoadResult<BusiObject>>(
					proxy, reader)
					{
				protected Object prepareLoadConfig(Object config) {
					config = super.prepareLoadConfig(config);
					 PagingLoadConfig pagingConfig = (PagingLoadConfig) config;

					 for(String str:storeinfoloader.getstoreinfoht().keySet())
					 {
						 pagingConfig.set(str, storeinfoloader.getstoreinfoht().get(str));
					 }
					 pagingConfig.set("Action","Loaddata");
					return config;
				}
				};
			
			return loader;
		}
	 
	 public void ExcJDBCSQL(java.util.Vector<String> v)
	 {
		 
			final com.base.myproject.client.tools.GreetingServiceAsync greetingService = GWT
			.create(com.base.myproject.client.tools.GreetingService.class);
	greetingService.saveBaseObject(v, null, new AsyncCallback<String>() {
		public void onFailure(Throwable caught) {
			// Show the RPC error message to the user
			System.out.println("error");
			
		}

		public void onSuccess(String result) {
			System.out.println(result);
			
		}
		});
		
	 }
	 public void ExcJDBCSQL(java.util.Vector<String> v,AsyncCallback<String> acb)
	 {
		 final com.base.myproject.client.tools.GreetingServiceAsync greetingService = GWT
			.create(com.base.myproject.client.tools.GreetingService.class);
		 greetingService.saveBaseObject(v, null, acb);
	 }
	 
	 /**
	  *   向服务器发送命令组，解决重复与服务器连接的问题。
	  * 同时服务器端支持回滚。
	  * 此做法合适提交给服务器的任务，返回成功或者失败，不合适用于取服务器的值等。
	  * 
	  * 
	  * @param list
	  * @param csro
	  */
	 public void sendCommandSync(CommandSyncContainer list,AsyncCallback<CommandSyncReturnObject> csro)
	 {
		 final com.base.myproject.client.tools.GreetingServiceAsync greetingService = GWT
			.create(com.base.myproject.client.tools.GreetingService.class);
		 greetingService.SendCommandSync(list,csro);
		 
		 
	 }
	 /**
	  * 发送jbpm命令
	  * 其中ratifyinfo里有命令的名称，根据命令的不同，应该传入相应的参数
	  * @see GreetingServiceImpl
	  * @param ratifyinfo
	  * @param csro
	  */
	 public void sendJBPMCommand(RatifyInfo ratifyinfo ,AsyncCallback<CommandSyncReturnObject> csro)
	 {
		 CommandSyncContainer list = new CommandSyncContainer();
		 CommandSyncJBPM cjbpm = new CommandSyncJBPM();
		 cjbpm.setRatifyinfo(ratifyinfo);
		 list.add(cjbpm);
		 sendCommandSync(list,csro);
	 }
}
